<template>
  <div class="min-h-screen bg-gradient-to-b from-blue-50 to-white">
    <!-- 顶部导航 -->
    <div class="bg-white shadow-sm">
      <div class="container mx-auto px-4 py-4 flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <button
            @click="goBack"
            class="text-gray-600 hover:text-gray-800 transition-colors"
          >
            <ArrowLeft class="w-6 h-6" />
          </button>
          <h1 class="text-xl font-bold text-gray-800">提交作文</h1>
        </div>
        
        <div class="flex items-center space-x-4">
          <span class="text-sm text-gray-600">{{ userStore.username || '用户' }}</span>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="container mx-auto px-4 py-8 max-w-4xl">
      <!-- 步骤指示器 -->
      <div class="mb-8">
        <div class="flex items-center justify-center">
          <div
            v-for="(step, index) in steps"
            :key="index"
            class="flex items-center"
          >
            <!-- 步骤圆圈 -->
            <div class="flex flex-col items-center">
              <div
                class="w-10 h-10 rounded-full flex items-center justify-center font-medium transition-all"
                :class="
                  index === 0
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-200 text-gray-600'
                "
              >
                {{ index + 1 }}
              </div>
              <span
                class="mt-2 text-sm font-medium"
                :class="
                  index === 0
                    ? 'text-blue-500'
                    : 'text-gray-500'
                "
              >
                {{ step }}
              </span>
            </div>
            
            <!-- 连接线 -->
            <div
              v-if="index < steps.length - 1"
              class="w-24 h-0.5 bg-gray-200 mx-4"
            ></div>
          </div>
        </div>
      </div>

      <!-- 表单卡片 -->
      <div class="bg-white rounded-xl shadow-sm p-6 md:p-8">
        <EssayForm
          ref="essayFormRef"
          :loading="loading"
          @submit="handleSubmit"
        />
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="mt-4 p-4 bg-red-50 border border-red-200 rounded-lg">
        <div class="flex items-start">
          <AlertCircle class="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
          <p class="ml-3 text-sm text-red-700">{{ error }}</p>
        </div>
      </div>

      <!-- 提示信息 -->
      <div class="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <div class="flex items-start">
          <Info class="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" />
          <div class="ml-3">
            <p class="text-sm text-blue-700 font-medium">温馨提示</p>
            <ul class="mt-2 text-sm text-blue-600 space-y-1">
              <li>• 作文内容需在 50-5000 字之间</li>
              <li>• 支持手动输入或上传图片识别</li>
              <li>• 选择合适的学段以获得更准确的批改</li>
              <li>• 提交后请耐心等待 AI 批改完成</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';
import { useEssayStore } from '../stores/essay';
import { ArrowLeft, AlertCircle, Info } from 'lucide-vue-next';
import EssayForm from '../components/EssayForm.vue';
import { getFriendlyErrorMessage } from '@/utils/errorMessages';
import { submitForCorrection } from '@/services/correctionApi';

const router = useRouter();
const userStore = useUserStore();
const essayStore = useEssayStore();

const essayFormRef = ref(null);
const loading = ref(false);
const error = ref('');

// 步骤
const steps = ['输入作文', '批改中', '查看结果'];

/**
 * 返回上一页
 * 优先使用浏览器历史记录返回，如果没有历史则返回首页
 */
const goBack = () => {
  // 检查是否有历史记录可以返回
  if (window.history.length > 1 && document.referrer) {
    router.back();
  } else {
    // 如果没有历史记录，返回到首页
    router.push({ name: 'home' });
  }
};

/**
 * 处理提交
 */
const handleSubmit = async (essayData) => {
  loading.value = true;
  error.value = '';
  
  try {
    console.log('[EssaySubmitPage] Submitting essay:', essayData.title);
    
    // 1. 创建作文
    const result = await essayStore.createEssay(essayData);
    
    if (result.success) {
      console.log('[EssaySubmitPage] Essay created:', result.data.id);
      
      // 2. 触发AI批改
      try {
        console.log('[EssaySubmitPage] Starting correction...');
        await submitForCorrection(result.data.id);
        console.log('[EssaySubmitPage] Correction submitted successfully');
        
        // 3. 跳转到批改结果页（添加fresh参数标记为新提交）
        router.push({
          path: `/correction/${result.data.id}`,
          query: { fresh: 'true' }  // 标记为新提交的批改
        });
      } catch (correctionErr) {
        console.error('[EssaySubmitPage] Correction failed:', correctionErr);
        // 批改失败，但作文已创建，跳转到历史记录页
        error.value = '作文提交成功，但批改失败。您可以在历史记录中重新批改';
        setTimeout(() => {
          router.push('/history');
        }, 2000);
      }
    }
  } catch (err) {
    console.error('[EssaySubmitPage] Submit failed:', err);
    
    // 使用友好的错误消息
    const friendlyMessage = getFriendlyErrorMessage(err);
    error.value = err.message || friendlyMessage || '作文提交失败，请检查网络后重试';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 无需额外样式，全部使用TailwindCSS */
</style>

